package cn.lisens.demo.service.impl;

import cn.lisens.demo.entity.User;
import cn.lisens.demo.service.UserService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * UserService的内存实现类
 */
@Service
public class UserServiceImpl implements UserService {
    
    // 使用线程安全的ConcurrentHashMap模拟数据库存储
    private final ConcurrentHashMap<String, User> userStorage = new ConcurrentHashMap<>();
    
    @Override
    public User createUser(User user) {
        if (user.getUserCode() == null || user.getUserCode().isEmpty()) {
            throw new IllegalArgumentException("用户编码不能为空");
        }
        
        if (userStorage.containsKey(user.getUserCode())) {
            throw new RuntimeException("用户编码已存在: " + user.getUserCode());
        }
        
        // 创建新用户并保存
        User newUser = new User();
        newUser.setUserCode(user.getUserCode());
        newUser.setUserName(user.getUserName());
        userStorage.put(newUser.getUserCode(), newUser);
        
        return newUser;
    }
    
    @Override
    public User getUserByCode(String userCode) {
        return userStorage.get(userCode);
    }
    
    @Override
    public List<User> getAllUsers() {
        return new ArrayList<>(userStorage.values());
    }
    
    @Override
    public User updateUser(String userCode, User user) {
        User existingUser = userStorage.get(userCode);
        if (existingUser == null) {
            throw new RuntimeException("用户不存在: " + userCode);
        }
        
        // 更新用户信息
        existingUser.setUserName(user.getUserName());
        return existingUser;
    }
    
    @Override
    public boolean deleteUser(String userCode) {
        return userStorage.remove(userCode) != null;
    }
}
